<template>
  <div
    v-show="visible"
    class="menu-content-attribute-relation-edge-context-menu"
    style=""
    :style="{
      top: offset.y + 'px',
      left: offset.x + 'px',
    }"
  >
    <div class="item">
      <modal-edit :id="activedEdgeId" :graph="graph" />
    </div>
    <div class="item">
      <modal-delete :id="activedEdgeId" :graph="graph" />
    </div>
  </div>
</template>
<script setup>
import { watch, ref, onMounted, onUnmounted } from 'vue'
import { EdgeEvent } from '@antv/g6'
import ModalDelete from './menu-content-attribute-relation-edge-context-menu-delete.vue'
import ModalEdit from './menu-content-attribute-relation-edge-context-menu-edit.vue'
/**
 * 外部参数
 */
let props = defineProps({
  graph: { required: true },
})

/**
 * 监听图事件
 */
let activedEdgeId = ref()
let visible = ref(false)
let offset = ref({ x: 0, y: 0 })
function onEnter(event) {
  let { target } = event
  props.graph.updateEdgeData([
    {
      id: target.id,
      style: {
        lineWidth: 3,
        labelFontWeight: 1000,
      },
    },
  ])
  props.graph.draw()
}
function onOut(event) {
  let { target } = event
  props.graph.updateEdgeData([
    {
      id: target.id,
      style: {
        lineWidth: 1,
        labelFontWeight: 100,
      },
    },
  ])
  props.graph.draw()
}
function onContextMenu(event) {
  console.log(event)
  offset.value = { x: event.client.x, y: event.client.y }
  visible.value = true
  activedEdgeId.value = event.target.id
}
watch(
  () => props.graph,
  (newGraph, oldGraph) => {
    if (newGraph) {
      newGraph.on(EdgeEvent.POINTER_ENTER, onEnter)
      newGraph.on(EdgeEvent.POINTER_OUT, onOut)
      newGraph.on(EdgeEvent.CONTEXT_MENU, onContextMenu)
    }
    if (oldGraph) {
      oldGraph.off(EdgeEvent.POINTER_ENTER, onEnter)
      oldGraph.off(EdgeEvent.POINTER_OUT, onOut)
      oldGraph.off(EdgeEvent.CONTEXT_MENU, onContextMenu)
    }
  },
  { immediate: true },
)

/**
 * 点击空白区域移除某些状态功能
 */
function onContextMenuDeleteEdgeClose() {
  visible.value = false
}
onMounted(() => {
  document.addEventListener('click', onContextMenuDeleteEdgeClose)
})
onUnmounted(() => {
  document.removeEventListener('click', onContextMenuDeleteEdgeClose)
})
</script>
<style lang="less" scoped>
.menu-content-attribute-relation-edge-context-menu {
  position: fixed;
  z-index: 1000;
  cursor: pointer;
  padding: 4px 0;
  background-color: #fff;
  box-shadow: 1px 2px 5px 0 rgba(0, 0, 0, 0.05);
  font-size: 14px;
  line-height: 30px;
  .item {
    &:hover {
      background: #ededed;
    }
  }
}
</style>
